@echo off
setlocal enabledelayedexpansion
REM By Joe 2023.7.10
REM Check if the parameters are empty
if "%~1"=="" (
    echo Please provide the file path to upload as the first parameter.
    exit /b
)

if "%~2"=="" (
    echo Please provide the target directory as the second parameter.
    exit /b
)

REM Set the file path and name
set "file_path=%~1"
set "file_name=%~nx1"

REM Check if the file exists
if not exist "%file_path%" (
    echo File "%file_path%" does not exist. Please check the file path.
    exit /b
)

REM Set the target directory
set "target_dir=%~2"

REM Connect to the Android device
adb root

REM Check if adb connection is successful
adb wait-for-device
if %errorlevel% neq 0 (
    echo Unable to connect to the Android device. Make sure the device is connected and developer options are enabled.
    exit /b
)

REM Upload the file to /sdcard/Download/
echo Uploading file "%file_path%" to the Android device...
adb push "%file_path%" "/sdcard/Download/%file_name%"
if %errorlevel% neq 0 (
    echo Failed to upload the file. Please check the file path and device connection.
    exit /b
)

REM Check if the file is successfully uploaded
adb shell ls "/sdcard/Download/%file_name%" > nul
if %errorlevel% neq 0 (
    echo Failed to upload the file. Please check the file path and device connection.
    exit /b
)

REM Remount the /vendor partition as writable
adb remount

REM Delete the old file if it exists
echo Deleting the old file "%target_dir%/%file_name%"...
adb shell rm "%target_dir%/%file_name%" > nul 2>&1

REM Move the new file to the target location
echo Moving the new file to "%target_dir%"...
adb shell mv "/sdcard/Download/%file_name%" "%target_dir%"
if %errorlevel% neq 0 (
    echo Failed to move the file. Please check the device connection and permissions.
    exit /b
)

REM Set file permissions and owner
echo Setting file permissions and owner...
adb shell chmod 644 "%target_dir%/%file_name%"
adb shell chown root "%target_dir%/%file_name%"
adb shell chgrp root "%target_dir%/%file_name%"

REM Reboot the device
echo Rebooting the device...
echo Script executed successfully.
exit /b
